#include "ctaskproc.h"

CTaskProc::CTaskProc(int id,QTcpSocket* &client, QString ip, int port, QObject *parent) :
    m_id(id),pLocalClient(client),m_ip(ip),m_port(port), QObject(parent)
{
    m_valid = true;
    connect(pLocalClient, SIGNAL(readyRead()), this , SLOT(recvClientData()));
    connect(pLocalClient, SIGNAL(disconnected()), this, SLOT(diconnect()));

    pToSvrClient = new QTcpSocket;
    connect(pToSvrClient, SIGNAL(readyRead()),this, SLOT(recvSvrData()));
    connect(pToSvrClient, SIGNAL(disconnected()),this, SLOT(diconnect()));
    connect(pToSvrClient,SIGNAL(error(QAbstractSocket::SocketError)),
                this,SLOT(procConnectErr(QAbstractSocket::SocketError)));
    connect(pToSvrClient, SIGNAL(connected()), this, SLOT(procConnectOk()));

    QHostAddress serverIP;
    serverIP.setAddress(m_ip);
    pToSvrClient->connectToHost(serverIP, m_port);

}

CTaskProc::~CTaskProc()
{
    pToSvrClient->close();
    pLocalClient->close();
    delete pToSvrClient;
    delete pLocalClient;
}
void CTaskProc::stop()
{
    m_valid = false;
    disconnect(pToSvrClient, SIGNAL(disconnected()),this, SLOT(diconnect()));
    disconnect(pLocalClient, SIGNAL(disconnected()), this, SLOT(diconnect()));
    pToSvrClient->close();
    pLocalClient->close();
}

void CTaskProc::recvClientData()
{
    while (pLocalClient->bytesAvailable()>0)
    {
        QByteArray datagram;

        datagram.resize(pLocalClient->bytesAvailable());

        pLocalClient->read(datagram.data(), datagram.size());

        pToSvrClient->write(datagram);

        emit sigReadLocalClientData(m_id,datagram);
    }
}

void CTaskProc::recvSvrData()
{
    while (pToSvrClient->bytesAvailable()>0)
    {
        QByteArray datagram;

        datagram.resize(pToSvrClient->bytesAvailable());

        pToSvrClient->read(datagram.data(), datagram.size());

        pLocalClient->write(datagram);
        emit sigReadSvrClientData(m_id,datagram);
    }
}

void CTaskProc::procConnectErr(QAbstractSocket::SocketError)
{
    qDebug()<<"to svr: "<<m_ip<<":"<<m_port<<": "<<pToSvrClient->errorString();
    pLocalClient->close();
}

void CTaskProc::procConnectOk()
{
    qDebug()<<"OnTaskStartOk: "<<m_id;
    emit sigTaskStartOk(m_id);
}


void CTaskProc::diconnect()
{
    if(m_valid)
    {
        m_valid = false;
        pToSvrClient->close();
        pLocalClient->close();
        emit sigTaskEnd(m_id);
    }
}

//发给svr的数据
void CTaskProc::sendToServer(QByteArray &data)
{
    pToSvrClient->write(data);
}

//发给dev的数据
void CTaskProc::sendToDevice(QByteArray &data)
{
    pLocalClient->write(data);
}
